package com.zte.rest;


import com.atlassian.confluence.core.ContentPermissionManager;
import com.atlassian.confluence.internal.ContentEntityManagerInternal;
import com.atlassian.confluence.search.ConfluenceIndexer;
import com.atlassian.confluence.security.SpacePermission;
import com.atlassian.confluence.security.SpacePermissionManager;
import com.atlassian.confluence.spaces.SpaceManager;
import com.atlassian.confluence.user.*;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import com.atlassian.user.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Path("/")
@Named("userGroupService")
public class UserGroupService {

    private static final Logger log = LoggerFactory.getLogger(UserGroupService.class);

    @ComponentImport
    protected UserAccessor userAccessor;

    @ComponentImport
    protected SpaceManager spaceManager;

    @ComponentImport
    protected SpacePermissionManager spacePermissionManager;

    @ComponentImport
    protected ContentPermissionManager contentPermissionManager;

    @ComponentImport
    protected GroupManager groupManager;

    @ComponentImport
    protected UserManager userManager;

    @ComponentImport
    protected ContentEntityManagerInternal contentEntityManagerInternal;

    @ComponentImport
    protected ConfluenceIndexer indexer;

    @ComponentImport
    protected PersonalInformationManager personalInformationManager;

    @Inject
    public UserGroupService(PersonalInformationManager personalInformationManager, ConfluenceIndexer indexer, UserAccessor userAccessor, SpaceManager spaceManager, SpacePermissionManager spacePermissionManager,
                            GroupManager groupManager, UserManager userManager, ContentEntityManagerInternal contentEntityManagerInternal,
                            ContentPermissionManager contentPermissionManager) {
        this.personalInformationManager = personalInformationManager;
        this.indexer = indexer;
        this.userAccessor = userAccessor;
        this.spaceManager = spaceManager;
        this.spacePermissionManager = spacePermissionManager;
        this.groupManager = groupManager;
        this.userManager = userManager;
        this.contentEntityManagerInternal = contentEntityManagerInternal;
        this.contentPermissionManager = contentPermissionManager;
    }

    @Path("closeUser")
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response closeUser(@QueryParam("optUser") String optUser, @QueryParam("closeUser") String closeUser) {
        Map result = new HashMap();
        if (StringUtils.isEmpty(optUser)) {
            result.put("code", "111111");
            result.put("message", "没有指定操作用户");
            return Response.ok(result).build();
        }
        List<String> groupNames = userAccessor.getGroupNamesForUserName(closeUser);
        ConfluenceUser user = userAccessor.getUserByName(closeUser);
        StringBuilder sb = new StringBuilder();
        try {
            spacePermissionManager.removeAllUserPermissions(user);
            contentPermissionManager.removeAllUserPermissions(user);
            for (String group : groupNames) {
                Group g = groupManager.getGroup(group);
                User u = userManager.getUser(closeUser);
                groupManager.removeMembership(g, u);
            }
        } catch (EntityException e) {
            e.printStackTrace();
            result.put("code", "111111");
            result.put("message", e.getMessage());
            return Response.ok(result).build();
        }

        result.put("code", "000000");
        result.put("message", "success");
        return Response.ok(result).build();
    }

    @Path("clearUser")
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response clearUser(@QueryParam("user") String closeUser) {
        Map result = new HashMap();
        ConfluenceUser optUser = AuthenticatedUserThreadLocal.get();
        if (!spacePermissionManager.hasPermissionNoExemptions(SpacePermission.CONFLUENCE_ADMINISTRATOR_PERMISSION, null, optUser)) {
            result.put("code", "111111");
            result.put("message", "用户没有操作权限");
            return Response.ok(result).build();
        }

        if (StringUtils.isEmpty(closeUser)) {
            result.put("code", "111111");
            result.put("message", "没有指定用户");
            return Response.ok(result).build();
        }
        List<String> groupNames = userAccessor.getGroupNamesForUserName(closeUser);
        ConfluenceUser user = userAccessor.getUserByName(closeUser);
        StringBuilder sb = new StringBuilder();
        try {
            spacePermissionManager.removeAllUserPermissions(user);
            contentPermissionManager.removeAllUserPermissions(user);
            for (String group : groupNames) {
                Group g = groupManager.getGroup(group);
                User u = userManager.getUser(closeUser);
                groupManager.removeMembership(g, u);
            }
        } catch (EntityException e) {
            e.printStackTrace();
            result.put("code", "111111");
            result.put("message", e.getMessage());
            return Response.ok(result).build();
        }

        result.put("code", "000000");
        result.put("message", "success");
        return Response.ok(result).build();
    }

    @Path("transUser")
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response transUser(@QueryParam("optUser") String optUser, @QueryParam("closeUser") String closeUser) {
        Map result = new HashMap();
        if (StringUtils.isEmpty(optUser)) {
            result.put("code", "111111");
            result.put("message", "没有指定操作用户");
            return Response.ok(result).build();
        }
        List<String> groupNames = userAccessor.getGroupNamesForUserName(closeUser);
        ConfluenceUser user = userAccessor.getUserByName(closeUser);
        StringBuilder sb = new StringBuilder();
        try {
            for (String group : groupNames) {
                if ("confluence-users".equals(group)) continue;
                Group g = groupManager.getGroup(group);
                User u = userManager.getUser(closeUser);
                groupManager.removeMembership(g, u);
            }
        } catch (EntityException e) {
            e.printStackTrace();
            result.put("code", "111111");
            result.put("message", e.getMessage());
            return Response.ok(result).build();
        }

        result.put("code", "000000");
        result.put("message", "success");
        return Response.ok(result).build();
    }

    @Path("addUserToGroup")
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response addUserToGroup(@QueryParam("user") String user, @QueryParam("group") String group) {
        Map result = new HashMap();
        try {
            Group g = groupManager.getGroup(group);
            User u = userManager.getUser(user);
            groupManager.addMembership(g, u);
        } catch (Exception e) {
            log.error("Failed to add user {} to group {}", user, group);
            result.put("code", "111111");
            result.put("message", "用户添加组失败");
            return Response.ok(result).build();
        }
        result.put("code", "000000");
        result.put("message", "success");
        return Response.ok(result).build();
    }

    @Path("removeUserFromGroup")
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response removeUserFromGroup(@QueryParam("user") String user, @QueryParam("group") String group) {
        Map result = new HashMap();
        try {
            Group g = groupManager.getGroup(group);
            User u = userManager.getUser(user);
            groupManager.removeMembership(g, u);
        } catch (Exception e) {
            log.error("Failed to remove user {} from group {}", user, group);
            result.put("code", "111111");
            result.put("message", "用户删除组失败");
            return Response.ok(result).build();
        }
        result.put("code", "000000");
        result.put("message", "success");
        return Response.ok(result).build();
    }

    @Path("createGroup")
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response createGroup(@QueryParam("group") String group) {
        Map result = new HashMap();
        try {
            groupManager.createGroup(group);
        } catch (Exception e) {
            log.error("Failed to create group {}" + group, group);
            result.put("code", "111111");
            result.put("message", "用户组创建失败");
            return Response.ok(result).build();
        }

        result.put("code", "000000");
        result.put("message", "success");
        return Response.ok(result).build();
    }

}